//
//  CustTableViewController.m
//  iTinyBag
//
//  Created by maxh on 1/5/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustTableViewController.h"

#define BAR_COLOR	[UIColor grayColor]
#define SELECTION_COLOR	[UIColor lightGrayColor]

static inline double radians (double degrees) {return degrees * M_PI/180;}

@implementation CustTableViewController
@synthesize dataSourceArr;
@synthesize filteredArr;
@synthesize selectedRows;
@synthesize searchBar;
@synthesize searchDC;

int currSelectedRow=-1;
BOOL IsDSSrchResults=FALSE;

- (void)viewCurrentContact
{
	if(currSelectedRow==-1)return;
	
	ABPersonViewController *pvc = [[[ABPersonViewController alloc] init] autorelease];
	NSArray *collection = IsDSSrchResults ? self.dataSourceArr : self.filteredArr;
	ABContact *contact = [collection objectAtIndex:currSelectedRow];
	/* 
	 UIAlertView *asv=[[UIAlertView alloc] initWithTitle:@"" message:[contact ToXMLString] delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
	 [asv show];
	 [asv release];
	 
	 
	 return;
	 */
	pvc.title=@"Detials";
	pvc.displayedPerson = contact.record;
	pvc.personViewDelegate = self;
	// pvc.allowsEditing = YES; // optional
	[[self navigationController] pushViewController:pvc animated:YES];
}

#pragma mark Table view methods

UIImage *defaultImg;

-(UIImage *)resizeImage:(UIImage *)image :(NSInteger) width :(NSInteger) height {
	
	CGImageRef imageRef = [image CGImage];
	CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
	CGColorSpaceRef colorSpaceInfo = CGColorSpaceCreateDeviceRGB();
	
	if (alphaInfo == kCGImageAlphaNone)
		alphaInfo = kCGImageAlphaNoneSkipLast;
	
	CGContextRef bitmap;
	
	if (image.imageOrientation == UIImageOrientationUp || image.imageOrientation == UIImageOrientationDown) {
		bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, alphaInfo);
		
	} else {
		bitmap = CGBitmapContextCreate(NULL, height, width, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, alphaInfo);
		
	}
	
	if (image.imageOrientation == UIImageOrientationLeft) {
		NSLog(@"image orientation left");
		CGContextRotateCTM (bitmap, radians(90));
		CGContextTranslateCTM (bitmap, 0, -height);
		
	} else if (image.imageOrientation == UIImageOrientationRight) {
		NSLog(@"image orientation right");
		CGContextRotateCTM (bitmap, radians(-90));
		CGContextTranslateCTM (bitmap, -width, 0);
		
	} else if (image.imageOrientation == UIImageOrientationUp) {
		NSLog(@"image orientation up");	
		
	} else if (image.imageOrientation == UIImageOrientationDown) {
		NSLog(@"image orientation down");	
		CGContextTranslateCTM (bitmap, width,height);
		CGContextRotateCTM (bitmap, radians(-180.));
		
	}
	
	CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
	CGImageRef ref = CGBitmapContextCreateImage(bitmap);
	UIImage *result = [UIImage imageWithCGImage:ref];
	
	CGColorSpaceRelease(colorSpaceInfo);
	CGContextRelease(bitmap);
	CGImageRelease(ref);
	
	return result;	
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 54;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView 
{ 
	return 1; 
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{
	// Normal table
	if (aTableView == self.tableView) 
		return self.dataSourceArr.count;
	
	// Search table
	self.filteredArr = [ABContactsHelper contactsMatchingName:self.searchBar.text];
	return self.filteredArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	// Dequeue or create a cell
	UITableViewCellStyle style =  UITableViewCellStyleSubtitle;
	UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:@"BaseCell"];
	if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease];
	
	NSArray *collection = (aTableView == self.tableView) ? self.dataSourceArr : self.filteredArr;
	ABContact *contact = [collection objectAtIndex:indexPath.row];
	cell.textLabel.text =[ contact.firstname stringByAppendingFormat:@" %@ %@",contact.lastname, contact.phonenumbers];
	cell.detailTextLabel.text = contact.emailaddresses;
	UIImage *img;
	if(contact.image==nil)
	{
		img=defaultImg ; 
	}
	else
	{
		img=[self resizeImage:contact.image :50 :50]; 
	}
	
	cell.imageView.image=img;
	
	cell.selectionStyle=UITableViewCellSelectionStyleGray;
	
	//cell.accessoryView=btnShareContactItem;
	return cell;
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue
{
	// Reveal the item that was selected
	if ([ABContact propertyIsMultivalue:property])
	{
		NSArray *array = [ABContact arrayForProperty:property inRecord:person];
		CFShow([array objectAtIndex:identifierForValue]);
	}
	else
	{
		id object = [ABContact objectForProperty:property inRecord:person];
		CFShow([object description]);
	}
	return YES;
}


- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section==-1) return;
	currSelectedRow=indexPath.row;
	IsDSSrchResults=(aTableView==self.tableView);
	UITableViewCell *selRow=[aTableView cellForRowAtIndexPath:indexPath];
	ABContact *contact=IsDSSrchResults?[self.dataSourceArr objectAtIndex:indexPath.row]:[self.filteredArr objectAtIndex:indexPath.row];
	
	NSNumber *recId= [[NSNumber alloc] initWithInt:((int)contact.recordID)];
	
	if(selRow.accessoryType==UITableViewCellAccessoryCheckmark)
	{
		selRow.accessoryType=UITableViewCellAccessoryNone;
		
		[selectedRows removeObject:recId];
	}else
	{
		selRow.accessoryType=UITableViewCellAccessoryCheckmark;
		
		if(!self.selectedRows)
			self.selectedRows=[[NSMutableArray alloc] init];
		
		[self.selectedRows addObject:recId];
	}
	//[contact release];
}

- (void) viewDidLoad
{
	defaultImg=[UIImage imageNamed:@"phone.png"];
	// Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.tintColor = BAR_COLOR;
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	
	self.tableView.tableHeaderView = self.searchBar;
	//self.tableView.
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	[self.searchDC setDelegate:self];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	filteredArr=nil;
	dataSourceArr=nil;
	searchBar=nil;
	searchDC=nil;
}

- (void)dealloc {
	[filteredArr release];
	[dataSourceArr release];
	[searchBar release];
	[searchDC release];
	[super dealloc];
}

@end

